package com.example.demo.zk;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CountDownLatch;

//@Component
public class ZkClient {
    ZooKeeper zooKeeper = null;
//    @PostConstruct
    public void init(){
        // 获取连接
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            zooKeeper = new ZooKeeper("192.168.56.102:2181", 3000, watchedEvent -> {
                Watcher.Event.KeeperState state = watchedEvent.getState();
                if (Watcher.Event.KeeperState.SyncConnected.equals(state) && Watcher.Event.EventType.None.equals(watchedEvent.getType())) {
                    System.out.println("获取连接");
                    countDownLatch.countDown();

                } else if (Watcher.Event.KeeperState.Closed.equals(state)) {
                    System.out.println("关闭连接");
                }
            });
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @PreDestroy
    public void destroy(){
        // 释放连接
        try {
            if (null != zooKeeper) {
                zooKeeper.close();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public ZkDistributeLock getLock(String lockName){
        return new ZkDistributeLock(zooKeeper,lockName);
    }
}
